import axios from 'axios'
import Qs from 'qs'

import { Message } from 'iview';

const CANCEL_TOKEN = axios.CancelToken
const AXIOS_SOURCE = CANCEL_TOKEN.source()

const ajax = {
    inject() {
        // 配置编码
        axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8'
        axios.defaults.headers.post['X-Requested-With'] = 'XMLHttpRequest'

    },
    all() {
        if (localStorage.getItem('token') !== null && localStorage.getItem('token') !== undefined) {
            axios.defaults.headers['token'] = localStorage.getItem('token')
        }
    },
    /**
     * 负责get请求
     * @param url ：请求的路径
     * @param params ：请求的参数
     * @param LoadingObj ：是否loading
     * @param downloadObj ：上传、下载的动作参数
     * @returns {Promise}
     */
    get(url, params, obj) {
        this.all()
        return new Promise(function (resolve, reject) {
            // if (url && url.indexOf('/') === 0) {
            //     url = `${url.substr(1)}?currentTime=${Date.now()}` // 加时间戳，避免IE浏览器get请求的缓存问题
            // }
            let config = {};

            config.params = Object.assign({}, params, obj);


            axios.get(url, config).then((res) => {
                let _data = res.data
                if (config.params.action == 'exists') {
                    if (_data.length !== 0 &&_data.resp_code === undefined) {
                        Message.warning('工号或学号已经存在')
                    }
                } else {
                    if (_data.code === 200 || _data.resp_code === 200) {
                        resolve(res.data || _data.datas)
                    } else if (_data.code === -1 || _data.resp_code === -1) {
                        reject(-1)
                        if (_data.resp_msg !== '不存在') {
                            Message.warning(_data.resp_msg)
                        }
                    }
                }
            }).catch(() => {
                Message.error('错误')
            })
        })
    },
    /**
     * 负责post请求
     * @param url ：请求的路径
     * @param params ：请求的参数
     * @param obj ：上传、下载的动作参数
     * @returns {Promise}
     */
    post(url, params, obj) {
        this.all()
        return new Promise(function (resolve, reject) {

            let config = {};
            if (obj && obj.action == 'upload') {
                config.headers = {
                    'Content-Type': 'multipart/form-data'
                };
            } else if (obj && obj.action == 'download') {
                config.responseType = 'blob';
            } else {
                obj = true;
                config.transformRequest = [item => {
                    return Qs.stringify(item, {
                        arrayFormat: 'repeat'
                    });
                }];
            }
            if (obj && obj.action == 'upload' || obj && obj.action == 'download') {
                let form = new FormData();
                for (let d in params) {
                    let v = params[d];
                    if (Object.prototype.toString.call(v) === '[object Array]') {
                        v.forEach(function (item) {
                            form.append(d, item);
                        });
                    } else {
                        form.append(d, v);
                    }
                }
                params = form;
            }

            axios.post(url, params, config).then((res) => {
                let _data = res.data
                // if (_data.code === 200 || _data.resp_code === 200) {
                    resolve(_data)
                // } else if (_data.code === 201 || _data.resp_code === 201) {
                //     Message.warning(_data.resp_msg)
                // } 
            }).catch(() => {
                Message.error('失败')
            })
        })
    },
    put(url, params) {
        return new Promise(function (resolve) {
            console.log(params)
            axios.put(url, params).then(res => {
                let _data = res.data
                if (_data.length !== 0) {
                    resolve(1)
                }
            }).catch(() => {
                Message.error('错误')
            })
        })
    },
    delete(url, params) {
        return new Promise(function (resolve) {
            console.log(params)
            axios.delete(url, params).then(res => {
                let _data = res.data
                if (_data.length !== 0) {
                    resolve(1)
                }
            }).catch(() => {
                Message.error('错误')
            })
        })
    },

    /* 取消请求  */
    __cancel() {
        AXIOS_SOURCE && AXIOS_SOURCE.cancel('AXIOS_CANCEL')
    }
}

ajax.inject()

export default ajax
